package entities.controllers;

import java.util.ArrayList;
import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;

import utils.Pair;
import utils.Utils;
import entities.kinds.Request;
import entities.pmf.PMF;

public class Requests {
	static final PersistenceManager pm = PMF.getInstance().getPersistenceManager();

	public static void add(String from, String to, String msg) {
		try {
			Request request = new Request();
			request.setFrom(Utils.SHA256(Utils.MD5(from)));
			request.setTo(Utils.SHA256(Utils.MD5(to)));
			request.setFromDec(from);
			request.setToDec(to);
			request.setMsg(msg);
			pm.makePersistent(request);
		} catch (Exception e) {
			System.out.println("request add err:" + e);
		}
	}

	public static ArrayList<Pair<String, String>> getByReceiver(String user) {
		Query q = pm.newQuery(Request.class);
		q.setFilter("to == to_");
		q.setFilter("read == false");
		q.declareParameters("String to_");
		q.setRange(0, 1000);
		@SuppressWarnings("unchecked")
		List<Request> res = (List<Request>) q.execute(user);
		ArrayList<Pair<String, String>> ret = new ArrayList<Pair<String, String>>();
		if (!res.isEmpty())
			for (Request r : res) {
				ret.add(new Pair<String, String>(r.getFromDec(), r.getMsg()));
				setAsRead(r);
			}
		return ret;
	}

	public static ArrayList<Pair<String, String>> getByReceiverAll(String user) {
		Query q = pm.newQuery(Request.class);
		q.setFilter("to == to_");
		q.setFilter("read == true");
		q.declareParameters("String to_");
		q.setRange(0, 1000);
		@SuppressWarnings("unchecked")
		List<Request> res = (List<Request>) q.execute(user);
		ArrayList<Pair<String, String>> ret = new ArrayList<Pair<String, String>>();
		if (!res.isEmpty())
			for (Request r : res) {
				ret.add(new Pair<String, String>(r.getFromDec(), r.getMsg()));
			}
		return ret;
	}

	public static ArrayList<Pair<String, String>> getBySender(String user) {
		Query q = pm.newQuery(Request.class);
		q.setFilter("from == from_");
		q.declareParameters("String from_");
		q.setRange(0, 1000);
		@SuppressWarnings("unchecked")
		List<Request> res = (List<Request>) q.execute(user);
		ArrayList<Pair<String, String>> ret = new ArrayList<Pair<String, String>>();
		if (!res.isEmpty())
			for (Request r : res) {
				ret.add(new Pair<String, String>(r.getToDec(), r.getMsg()));
			}
		return ret;
	}

	private static void setAsRead(Request r) {
		try {
			pm.currentTransaction().begin();
			r.setRead(true);
			pm.currentTransaction().commit();
		} catch (Exception e) {
			pm.currentTransaction().rollback();
			System.out.println("request upd err:" + e);
		}
	}

}
